package com.pkk.cloud.support.gateway.limiter.global.config;

import static com.pkk.cloud.support.gateway.limiter.global.constand.GlobalLimitConstand.DEFAULT_GLOBAL_LIMIT;

import com.google.common.util.concurrent.RateLimiter;
import com.pkk.cloud.support.gateway.limiter.global.properties.GlobalRateLimitProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

/**
 * @description: 全局限制的配置
 * @author: peikunkun
 * @create: 2020-03-24 11:07
 **/
@Slf4j
public class GlobalLimitConfig implements CommandLineRunner {

  @Autowired
  private GlobalRateLimitProperties globalRateLimitProperties;
  /**
   * 全局限制
   */
  private static Integer GLOBAL_LIMIT = -1;

  /**
   * 全局请求限制
   */
  public static RateLimiter GLOBAL_RATE_LIMITER = null;

  /**
   * @Description: 初始化此配置
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/3/24 0024 下午 1:31
   */
  public void init() {
    //初始化默认的配置
    if (null != globalRateLimitProperties && globalRateLimitProperties.isEnable()) {
      GLOBAL_LIMIT = globalRateLimitProperties.getLimitNum();
    }

    if (null == GLOBAL_LIMIT) {
      GLOBAL_LIMIT = DEFAULT_GLOBAL_LIMIT;
    }

    //小于零-手动设置理想性的无限大不限制
    if (GLOBAL_LIMIT < 0) {
      GLOBAL_LIMIT = 999999;
    }

    //每秒产生默认#getLimit个令牌
    GLOBAL_RATE_LIMITER = RateLimiter.create(GLOBAL_LIMIT);
    log.info("[网关服务]-[全局每秒请求最大限制次数]-[{}]", GLOBAL_LIMIT);
  }


  @Override
  public void run(String... args) throws Exception {
    //初始化限流配置
    this.init();
  }
}
